package com.gome.ocean.controller.authority;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.elasticsearch.common.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.Page;
import com.gome.framework.util.BeanUtil;
import com.gome.framework.util.StringUtil;
import com.gome.ocean.common.enums.authority.UrlMethodType;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.Function;
import com.gome.ocean.dao.model.authority.Module;
import com.gome.ocean.service.authority.FunctionService;
import com.gome.ocean.service.authority.ModuleService;
import com.gome.ocean.service.base.BaseController;
import com.google.common.collect.Maps;

/**
 * Created by liuqingxia on 2016/6/6.
 */
@Controller
@RequestMapping("/function")
public class FunctionController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(FunctionController.class);

    @Autowired
    private FunctionService functionService;
    @Autowired
    private ModuleService   moduleService;

    @RequestMapping(value = "/toInsertPage", method = RequestMethod.GET)
    public ModelAndView toInsertPage(ModelAndView mav) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Module> list = moduleService.findAllModuleByMap(map);
        mav.addObject("moduleList", list);
        mav.setViewName("authority/function/insert");
        return mav;
    }

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage insert(HttpServletRequest req) {
        ResponsePage response = getResponsePage();
        String name = getParamValue("name");
        if (StringUtil.isBlank(name)) {
            return response.setErrorMsg("请设置功能名称");
        }
        String url = getParamValue("url");
        if (StringUtil.isBlank(url)) {
            return response.setErrorMsg("请设置url地址");
        }
        int methodType = getIntParamValue("methodType");
        UrlMethodType urlMethodType = UrlMethodType.getUrlMethodType(methodType);
        if (null == urlMethodType) {
            return response.setErrorMsg("urlMethodType参数不符合规范");
        }
        Function function = assemblyFunction();
        String moduleName = req.getParameter("moduleName");
        function.setModuleName(moduleName);
        function.setCreateTime(new Date());
        List<Function> funLists = functionService.findFuncByUrlAndType(function.getUrl(), function.getMethodType());
        if (funLists != null && funLists.size() > 0) {
            return response.setErrorMsg("url与方法类型已经存在，请不要重复添加！");
        }
        try {
            if (functionService.insertFunction(function)) {
                return response.setSuccessMsg("新建功能成功");
            }
            return response.setErrorMsg("新建功能失败");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(e.getMessage());
        }
    }

    private Function assemblyFunction() {
        Map<String, Object> params = getParamsMap();
        Function function = new Function();
        try {
            BeanUtil.copyProperties(params, function);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return function;
    }

    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage remove(@RequestParam("id") Long id) {
        ResponsePage response = getResponsePage();
        try {
            if (functionService.removeFunction(id)) {
                return response.setSuccessMsg("删除成功");
            }
            return response.setErrorMsg("删除失败");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage update(HttpServletRequest req) {
        ResponsePage response = new ResponsePage();
        String name = req.getParameter("name");
        if (StringUtil.isBlank(name)) {
            return response.setErrorMsg("请设置功能名称");
        }
        String url = req.getParameter("url");
        if (StringUtil.isBlank(url)) {
            return response.setErrorMsg("请设置url地址");
        }
        int methodType = Integer.parseInt(req.getParameter("methodType"));
        UrlMethodType urlMethodType = UrlMethodType.getUrlMethodType(methodType);
        if (null == urlMethodType) {
            return response.setErrorMsg("urlMethodType参数不符合规范");
        }
        Function function = assemblyFunction();
        String moduleName = req.getParameter("moduleName");
        function.setModuleName(moduleName);
        function.setUpdateTime(new Date());

        try {
            if (functionService.updateFunction(function)) {
                return response.setSuccessMsg("修改成功");
            }
        } catch (Exception e) {
            LOG.error(e.toString());
            return response.setErrorMsg("异常信息：" + e.toString());
        }
        return response.setErrorMsg("修改失败");
    }

    @RequestMapping(value = "/toFindPage", method = RequestMethod.GET)
    public ModelAndView toFindPage(ModelAndView mav) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Module> moduleList = moduleService.findAllModuleByMap(map);
        mav.addObject("moduleList", moduleList);
        mav.setViewName("authority/function/find");
        return mav;
    }

    @RequestMapping(value = "/find", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage find() {
        ResponsePage response = getResponsePage();
        int pageNum = getPageNum();
        int pageSize = getPageSize();
        try {
            Page<Function> functions = functionService.findAllFunctions(pageNum, pageSize);
            if (null == functions || 0 == functions.size()) {
                return response.setSuccessMsg("未查询到结果");
            }
            return response.setPage(functions, "查询成功");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping(value = "/findByUrl", method = RequestMethod.POST)
    @ResponseBody
    public ResponsePage findByUrl(@RequestParam("url") String url) {
        ResponsePage response = getResponsePage();
        try {
            List<Function> functions = functionService.findFunctionByUrl(url);
            if (null == functions || 0 == functions.size()) {
                return response.setSuccessMsg("未查询到结果");
            }
            return response.setJustList(functions, "查询成功");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return response.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping("/batchUpdateData")
    @ResponseBody
    public Map<String, Object> batchUpdateData(HttpServletRequest request, String tableName, String fieldName) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            if (StringUtils.isNotBlank(tableName) && StringUtils.isNotBlank(fieldName)) {
                Map<String, Object> paramMap = Maps.newHashMap();
                paramMap.put("tableName", tableName);
                paramMap.put("fieldName", fieldName);
                boolean flag = functionService.batchUpdateSqlValue(paramMap);
                if (flag) {
                    map.put("root", "批量更新成功");
                    map.put("success", true);
                    map.put("failure", false);
                } else {
                    map.put("root", "批量更新失败");
                    map.put("success", false);
                    map.put("failure", true);
                }
            } else {
                map.put("root", "批量更新失败,参数为空");
                map.put("success", false);
                map.put("failure", true);
            }
        } catch (Exception e) {
            map.put("root", "批量更新失败,原因" + e.getMessage());
            map.put("success", false);
            map.put("failure", true);
        }
        return map;
    }

}
